package com.liyiqing.secondhandmall.productservice.exception;

import com.liyiqing.commonservice.utils.R;
import com.liyiqing.commonservice.utils.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.liyiqing.secondhandmall.productservice.controller")
public class ExceptionControllerAdvice {

    /**
     * 数据校验的异常处理
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        BindingResult result  = e.getBindingResult();
        Map<String ,String> map = new HashMap<>();
            //获取校验的错误结果
            result.getFieldErrors().forEach((item)->{
                //获取错误的属性名
                String field =  item.getField();
                //获取错误提示
                String message = item.getDefaultMessage();
                map.put(field,message);
            });
        return R.error(StatusCode.VALID_EXCEPTION.getCode(),StatusCode.VALID_EXCEPTION.getMsg()).put("data",map);
    }


    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        return R.error();
    }

}
